import React, { useEffect, useState } from 'react'
import {
  Button,
  message,
  Space,
  Table,
  Dropdown,
  Checkbox,
  Drawer,
  Modal,
  notification,
  Form,
  DatePicker,
  Spin,
  Tooltip,
} from 'antd'
import useGetTableData from '@/hooks/useGetTableDataV2'
import SearchForm from '@/components/QsfCustomForm/SearchForm'
import { useForm } from 'antd/es/form/Form'
import PageContainer from '@/components/PageContainer'
import { useIndexColumns, useInnerColumns } from './columns'
import { searchConfig } from './FormConfig'
import { ITableData, ReserveInvoiceDetailVO, SupplierTransportAddressVO } from './types'
import { EditFormVertical } from '@/components/CustomForm'
import CustomTable from '@/components/CustomTable'
import { applicationTypeEnum, OperationLogType } from '@/constant'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useAppSelector } from '@/store/hooks'
import './index.less'
import { DownOutlined, ExclamationCircleOutlined, PlusOutlined, TruckOutlined, UploadOutlined } from '@ant-design/icons'
import { getProductClassConfigByType, getSpuOptions, reserveInvoiceExport } from '@/api/goods'
import dayjs from 'dayjs'
import {
  exportOutNoticeOrder,
  fixArrivalTime,
  reserveInvoiceBatchAudit,
  reserveInvoicebatchCancel,
  reserveInvoiceDelivery,
  reserveInvoicePush,
  reserveInvoiceQuery,
  submitBoxLoad,
} from '@/api/purchase'
import { useFormDelivery, useFormViewDelivery } from './useForm'
import { getSupplierList } from '@/api/supplier'
import { downloadByOwnUrl, exportNotification, getRecentMonths } from '@/utils/util'
import useSearchUser from '@/hooks/useSearchUser'
import LogsDrawer from '@/components/LogsDrawer'
import useViewLogs from '@/hooks/useViewLogs'
import PermissionButton from '@/components/PermissionButton'
import useSearchSupplier from '@/hooks/useSearchSupplier'
import useCachePage from '@/hooks/useCachePage'
import useModal from '@/hooks/useModal'
import GenerateModal from './components/GenerateModal'
import AddressModal from './components/AddressModal'
import { addAddressReq, createTransportationOrder, getSupplierAddressData } from '@/api/logistics'
const Index: React.FC = () => {
  let SpuTimeout: ITimeoutType
  const navigate = useNavigate()
  const [form] = useForm()
  const [FormDelivery] = useForm()
  const [FormViewDelivery] = useForm()
  const [FormSend] = useForm()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const [deliveryModalShow, setdeliveryModalShow] = useState<boolean>(false)
  const [expand, setexpand] = useState<boolean>(false)
  const [selectedRowKeys, setselectedRowKeys] = useState<React.Key[]>([])
  const [selectedRowInfos, setselectedRowInfos] = useState<ITableData[]>([])
  const [SpuOptions, setSpuOptions] = useState<IOptionItem[]>([])
  const [SkuOptions, setSkuOptions] = useState<IOptionItem[]>([])
  const [addressList, setaddressList] = useState<SupplierTransportAddressVO[]>([])
  const [exportLoading, setexportLoading] = useState(false)
  const [isModalShow, setisModalShow] = useState<boolean>(false)
  const [spinning, setspinning] = useState<boolean>(false)
  //大类
  const [classBig, setclassBig] = useState<IOptionItem[]>([])
  const [CurrentInfo, setCurrentInfo] = useState<Record<string, any>>({})
  // 日志
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'reserveInvoiceCode',
    OperationLogType.RESERVEINVOICE,
  )
  // 承运商
  const [SupplierCYOption, setSupplierCYOption] = useState<IOptionItem[]>([])
  const [expandedRowKeys, setexpandedRowKeys] = useState<React.Key[]>([])
  const [viewdeliveryModalShow, setviewdeliveryModalShow] = useState(false)
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const [menuItems, setmenuItems] = useState<{ key: string; label: string }[]>([])
  const { SupplierOption, handleSearchSupplier, setSupplierOption } = useSearchSupplier('supplierId')
  const applicationId = useAppSelector((state) => state.user.user_info.applicationId)
  const isRoot = applicationId == applicationTypeEnum.SOP_SEVENFUN_WEB
  const defaultDateRange = getRecentMonths('YYYY-MM-DD HH:mm:ss')
  const { UserOptions, handleSearchUser, setUserOptions } = useSearchUser()
  const [query] = useSearchParams()
  const reserveInvoiceCode = query.get('reserveInvoiceCode') || ''
  const customSearchType = query.get('customSearchType') || ''
  const { setCachePage, getCachePage } = useCachePage()
  const { tableProps, params, setParams, search, reset, reload } = useGetTableData<ITableData>(reserveInvoiceQuery, {
    form: form,
    defaultFieldsParams: {
      createTimeStart: reserveInvoiceCode ? null : defaultDateRange,
      reserveInvoiceStatuses: reserveInvoiceCode ? null : [1, 2, 3, 4, 6],
      reserveInvoiceCodes: reserveInvoiceCode ? [reserveInvoiceCode] : null,
    },
    immediatelySend: false,
    cachePageCallback: (current, size, prevSize) => {
      const cacheData = getCachePage()
      setCachePage({
        ...cacheData,
        current: prevSize === size ? current : 1,
        size,
      })
    },
    paramsCallback: (reqParams) => {
      return {
        ...reqParams,
        createTimeStart:
          reqParams.createTimeStart && reqParams.createTimeStart.length === 2 ? reqParams.createTimeStart[0] : null,
        createTimeEnd:
          reqParams.createTimeStart && reqParams.createTimeStart.length === 2 ? reqParams.createTimeStart[1] : null,
        scheduleDeliveryTimeStart:
          reqParams.scheduleDeliveryTimeStart && reqParams.scheduleDeliveryTimeStart.length === 2
            ? reqParams.scheduleDeliveryTimeStart[0]
            : null,
        scheduleDeliveryTimeEnd:
          reqParams.scheduleDeliveryTimeStart && reqParams.scheduleDeliveryTimeStart.length === 2
            ? reqParams.scheduleDeliveryTimeStart[1]
            : null,
        estimatedArrivalTimeStart:
          reqParams.estimatedArrivalTimeStart && reqParams.estimatedArrivalTimeStart.length === 2
            ? reqParams.estimatedArrivalTimeStart[0]
            : null,
        estimatedArrivalTimeEnd:
          reqParams.estimatedArrivalTimeStart && reqParams.estimatedArrivalTimeStart.length === 2
            ? reqParams.estimatedArrivalTimeStart[1]
            : null,
        lastArrivalTimeStart:
          reqParams.lastArrivalTimeStart && reqParams.lastArrivalTimeStart.length === 2
            ? reqParams.lastArrivalTimeStart[0]
            : null,
        lastArrivalTimeEnd:
          reqParams.lastArrivalTimeStart && reqParams.lastArrivalTimeStart.length === 2
            ? reqParams.lastArrivalTimeStart[1]
            : null,
        reserveInvoiceCodes: reqParams?.reserveInvoiceCodes != null ? reqParams.reserveInvoiceCodes : null,
        purchaseOrderCodes: reqParams?.purchaseOrderCodes != null ? reqParams.purchaseOrderCodes : null,
        orderSources: reqParams.orderSources ? [reqParams.orderSources] : null,
      }
    },
  })
  const FixModal = useModal({
    onSuccess: () => {
      message.success('操作成功')
      reload()
    },
  })
  const GenerateModalInstance = useModal({
    onSuccess: () => {
      message.success('操作成功')
      setselectedRowKeys([])
      setselectedRowInfos([])
      reload()
    },
  })
  const AddressModalInstance = useModal({
    onSuccess: () => {
      message.success('操作成功')
      AddressModalInstance?.form.resetFields()
      getAddressList()
    },
    autoClose: false,
  })
  useEffect(() => {
    getProductClassConfig()
    getSupList('')
    handleCacheData()
  }, [])
  useEffect(() => {
    const items: { key: string; label: string }[] = []
    if (buttonCodeList.includes('pushDeliver')) {
      items.push({
        key: 'PUSH',
        label: '触发CB推送',
      })
    }
    setmenuItems(items)
    const data = tableProps.dataSource.map((item) => item.reserveInvoiceId)
    if (expand) {
      setexpandedRowKeys(data)
    } else {
      setexpandedRowKeys([])
    }
  }, [tableProps.dataSource, expand])
  const handleCacheData = async () => {
    if (customSearchType === '1') {
      form.resetFields()
      form.setFieldsValue({
        reserveInvoiceStatuses: [1],
      })
      setTimeout(async () => {
        search()
      }, 1)
      return
    }
    const cacheData = getCachePage()
    if (cacheData == null || reserveInvoiceCode) {
      search()
      setCachePage({ ...params })
    } else {
      const { SupplierOption, SpuOptions, UserOptions, ...resetCacheData } = cacheData
      // 先重置表单再设置缓存！！！
      form.resetFields()
      form.setFieldsValue({
        ...resetCacheData,
      })
      setSupplierOption(SupplierOption || [])
      setUserOptions(UserOptions || [])
      setSpuOptions(SpuOptions || [])
      reload({ ...resetCacheData })
    }
  }
  const onCancel = () => {
    setCurrentInfo({})
    setdeliveryModalShow(false)
    setviewdeliveryModalShow(false)
    FormDelivery.resetFields()
    setisModalShow(false)
    FormSend.resetFields()
  }
  const selectRows = (keys: React.Key[], info: ITableData[]) => {
    setselectedRowKeys(keys)
    setselectedRowInfos(info)
  }
  const expandedRowRender = (rows: ReserveInvoiceDetailVO) => {
    return (
      <Table
        rowKey={(rows) => rows.reserveInvoiceDetailId}
        columns={useInnerColumns()}
        dataSource={rows.detailVOS || []}
        pagination={false}
        scroll={{
          x: 'max-content',
        }}
        rowHoverable={false}
        rowClassName={(_, index) => {
          return index % 2 === 0 ? '' : 'zebra-row-odd'
        }}
      />
    )
  }
  const getAddressList = async () => {
    const res = await getSupplierAddressData<SupplierTransportAddressVO>({
      supplierId: selectedRowInfos[0]?.supplierId,
    })
    if (res?.code == 200) {
      const data = res?.data || []
      setaddressList(data)
    }
  }
  const getProductClassConfig = async (type: 1 | 2 | 3 | 4 = 1) => {
    const res = await getProductClassConfigByType<{
      className: string
      classConfigId: string | number
    }>({ type, auth: 1 })
    const classIdOptions =
      res?.data?.map((item) => {
        return {
          label: item.className,
          value: item.classConfigId,
          isLeaf: false,
        }
      }) || []
    setclassBig(classIdOptions)
  }
  const handleSearchSpuOptions = (newValue = '') => {
    if (!newValue) return
    if (SpuTimeout) {
      clearTimeout(SpuTimeout)
      SpuTimeout = null
    }
    const getOptions = async () => {
      const res = await getSpuOptions<{
        spuName: string
        spuCode: string
        designCode: string
      }>({ keyword: newValue })
      if (res.code === 200) {
        const data =
          res?.data?.map((item) => {
            return {
              label: `${item?.spuCode}｜${item.spuName}${item?.designCode ? '｜' + item?.designCode : ''}`,
              value: item.spuCode,
            }
          }) || []
        setSpuOptions(data)
      }
    }
    SpuTimeout = setTimeout(getOptions, 500)
  }
  const onView = (info: ITableData) => {
    setCurrentInfo(info)
    setviewdeliveryModalShow(true)
  }
  const onViewLogs = (info: ITableData) => {
    viewLogs(info)
  }
  const onConfirmDelivery = (info: ITableData) => {
    setCurrentInfo(info)
    setdeliveryModalShow(true)
  }
  const onSubmitPacking = (info: ITableData) => {
    setCurrentInfo(info)
    setisModalShow(true)
  }
  const onFix = (info: ITableData) => {
    const { updateArrivalTimeRemark, ...resetparams } = info
    FixModal.openModal(resetparams)
  }
  const onDel = async (info: ITableData) => {
    const instance = Modal.confirm({
      title: '提示',
      content: (
        <div style={{ color: 'red' }}>取消预约后，无法再对订单执行任何操作，订单下的箱唛将失效，确认要操作吗?</div>
      ),
      okText: '确认',
      cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      onOk: async () => {
        const res = await reserveInvoicebatchCancel({
          cancelDetails: [{ reserveInvoiceCode: info.reserveInvoiceCode, orderSource: info.orderSource }],
        }).finally(() => {
          instance.destroy()
          reload()
        })
        if (res.code === 200) {
          message.success('操作成功')
        }
        if (res.code === 820000 && res.failInfo) {
          const failInfo = JSON.parse(res.failInfo)?.map((item: { failCode: string; failMsg: string }) => {
            return (
              <div key={item.failCode + item.failMsg}>
                {item.failCode}，{item.failMsg}
              </div>
            )
          })
          notification.open({
            type: 'warning',
            message: res.msg,
            description: failInfo,
          })
        }
      },
    })
  }
  const getSupList = async (newValue: string) => {
    const res = await getSupplierList<{ supplierName: string; supplierId: string }>({
      supplierClassificationCode: '承运商',
      keyword: newValue,
      useStatus: 1,
      // 0 不鉴权
      authSupplier: 0,
    })
    if (res.code === 200) {
      const SupplierCYOption =
        res?.data?.list?.map((item) => {
          return {
            label: item.supplierName,
            value: item.supplierId,
          }
        }) || []
      setSupplierCYOption(SupplierCYOption)
    }
  }
  const onDelivery = async (values: any) => {
    const paramsData = {
      ...values,
      estimatedArrivalTime:
        values.estimatedArrivalTime && dayjs(values.estimatedArrivalTime).format('YYYY-MM-DD HH:mm:ss'),
      reserveInvoiceCode: CurrentInfo.reserveInvoiceCode,
      autoCall: false,
    }
    const res = await reserveInvoiceDelivery(paramsData).finally(() => {
      reload()
      onCancel()
    })
    if (res.code === 200) {
      message.success('操作成功')
    }
    if (res.code === 820000 && res.failInfo) {
      const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
        return <div key={item}>{item}</div>
      })
      notification.open({
        type: 'warning',
        message: res.msg,
        description: failInfo,
      })
    }
  }
  const handleClickMore = async (info: any) => {
    if (selectedRowKeys.length === 0) {
      message.warning('请勾选需要操作的列表数据！')
      return
    }
    if (info.key == 'PUSH') {
      const res = await reserveInvoicePush({
        reserveInvoiceCodes: selectedRowInfos.map((item) => item.reserveInvoiceCode),
      })
      if (res.code === 200) {
        message.success('触发推送成功，请稍后查看！')
        setselectedRowKeys([])
        setselectedRowInfos([])
        reload()
      }
    }
  }
  const onSendOk = async () => {
    const data = await FormSend.validateFields()
    const paramData = {
      purchaseOrderCode: CurrentInfo?.detailVOS[0]?.purchaseOrderCode,
      reserveInvoiceCode: CurrentInfo.reserveInvoiceCode,
      scheduleDeliveryTime:
        data?.scheduleDeliveryTime && dayjs(data.scheduleDeliveryTime).format('YYYY-MM-DD HH:mm:ss'),
    }
    const res = await submitBoxLoad({ ...paramData, skipBoxCheck: 0 })
    if (res.code === 200) {
      message.success('操作成功')
      reload()
      onCancel()
    }
    if (res?.code == 820000 && !res?.data && typeof res?.msg === 'string') {
      Modal.confirm({
        title: '提示',
        content: '物流需求单已预约，若存在箱包数变更，请及时重新预约或线下通知物流商！',
        okText: '确认',
        cancelText: '取消',
        icon: <ExclamationCircleOutlined />,
        onOk: async () => {
          const res = await submitBoxLoad({ ...paramData, skipBoxCheck: 1 })
          if (res.code === 200) {
            message.success('操作成功')
            reload()
            onCancel()
          }
        },
      })
    }
  }
  return (
    <PageContainer className="purchase_delivery_page">
      <SearchForm
        loading={tableProps.loading}
        form={form}
        searchConfig={searchConfig({
          DICTDATA,
          classBig,
          SupplierOption,
          SkuOptions,
          handleSearchSupplier,
          UserOptions,
          handleSearchUser,
          SpuOptions,
          handleSearchSpuOptions,
          isRoot,
        })}
        onFinish={() => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          setCachePage({
            ...form.getFieldsValue(),
            SupplierOption,
            SpuOptions,
            UserOptions,
            current: 1,
            size: params.size,
          })
          search()
        }}
        onReset={() => {
          setselectedRowKeys([])
          setselectedRowInfos([])
          reset()
          setCachePage({
            current: 1,
            size: 10,
            createTimeStart: reserveInvoiceCode ? null : defaultDateRange,
            reserveInvoiceStatuses: reserveInvoiceCode ? null : [1, 2, 3, 4, 6],
            reserveInvoiceCodes: reserveInvoiceCode ? [reserveInvoiceCode] : null,
          })
        }}
        extra={
          <div className="table_extra_flex_wrapbox">
            <div className="table_extra_flex">
              <PermissionButton
                icon={<PlusOutlined />}
                permission="deliver"
                type="primary"
                onClick={() => {
                  navigate('/purchase/delivery/add')
                }}
                disabled={tableProps.loading}
              >
                新建预约发货单
              </PermissionButton>
              <PermissionButton
                icon={<TruckOutlined style={{ fontSize: 18 }} />}
                permission="CreateLogisticsDemand"
                type="primary"
                onClick={() => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  if (
                    selectedRowInfos.some((item) => item.reserveInvoiceStatus == 4 || item.reserveInvoiceStatus == 5)
                  ) {
                    message.warning('已收货或已取消的预约发货单不支持创建物流需求！')
                    return
                  }
                  const hasOrderedList = selectedRowInfos?.filter((item) => item.transportationOrderCode)
                  const failInfo = hasOrderedList?.map((item) => {
                    return <div key={item.reserveInvoiceCode}>{item?.reserveInvoiceCode}已经下过物流需求单了</div>
                  })
                  if (hasOrderedList && hasOrderedList.length > 0) {
                    notification.open({
                      type: 'warning',
                      message: '提示',
                      description: failInfo,
                    })
                    return
                  }
                  const firstSupplierId = selectedRowInfos[0].supplierId
                  if (selectedRowInfos.some((item) => item.supplierId != firstSupplierId)) {
                    message.warning('不支持跨供应商合并发起预约发货单！')
                    return
                  }
                  GenerateModalInstance.openModal({ dataSource: selectedRowInfos })
                  getAddressList()
                }}
                disabled={tableProps.loading}
              >
                发起物流需求
              </PermissionButton>
              <PermissionButton
                disabled={tableProps.loading}
                permission="printBoxLabel"
                onClick={() => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const waitScanCodes = selectedRowInfos.filter((item) => item.reserveInvoiceStatus == 6)
                  if (waitScanCodes.length > 0) {
                    notification.warning({
                      message: '待扫码状态的预约发货单请前往【扫码装箱-箱唛】页面打印箱唛',
                      description: waitScanCodes?.map((item: any, index) => (
                        <div key={index}>{item?.reserveInvoiceCode}</div>
                      )),
                    })
                    return
                  }
                  const reserveInvoiceCodes = selectedRowInfos
                    ?.filter((item) => item.orderSource == 1)
                    ?.filter(
                      (item) =>
                        !(
                          item.reserveInvoiceStatus == 2 ||
                          item.reserveInvoiceStatus == 3 ||
                          item.reserveInvoiceStatus == 4
                        ),
                    )
                    ?.map((item) => item.reserveInvoiceCode)
                  if (reserveInvoiceCodes.length > 0) {
                    notification.warning({
                      message: '不符合打印条件',
                      description: reserveInvoiceCodes?.map((item: any, index) => <div key={index}>{item}</div>),
                    })
                    return
                  }
                  navigate('/print?type=3', {
                    state: {
                      params: selectedRowInfos.map((item) => item.reserveInvoiceCode),
                    },
                  })
                }}
              >
                打印箱唛
              </PermissionButton>
              <PermissionButton
                disabled={tableProps.loading || exportLoading}
                permission="checkDeliver"
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const reserveInvoiceCodes = selectedRowInfos?.map((item) => item.reserveInvoiceCode)
                  setexportLoading(true)
                  const res = await reserveInvoiceBatchAudit({ reserveInvoiceCodes }).finally(() => {
                    setexportLoading(false)
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                    reload()
                  })
                  if (res.code === 200) {
                    message.success('操作成功')
                  }
                  if (res.code === 820000 && res.failInfo) {
                    const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
                      return <div key={item}>{item}</div>
                    })
                    notification.open({
                      type: 'warning',
                      message: res.msg,
                      description: failInfo,
                    })
                  }
                }}
              >
                发货审核
              </PermissionButton>
              <PermissionButton
                disabled={tableProps.loading || exportLoading}
                permission="printNotice"
                onClick={async () => {
                  if (selectedRowKeys.length === 0) {
                    message.warning('请勾选需要操作的列表数据！')
                    return
                  }
                  const reserveInvoiceCodes = selectedRowInfos?.map((item) => item.reserveInvoiceCode)
                  setexportLoading(true)
                  const res = await exportOutNoticeOrder({ reserveInvoiceCodes }).finally(() => {
                    setexportLoading(false)
                    setselectedRowKeys([])
                    setselectedRowInfos([])
                  })
                  if (res.code === 200) {
                    downloadByOwnUrl(res.data)
                    message.success('操作成功')
                  }
                  if (res.code === 820000 && res.failInfo) {
                    const failInfo = JSON.parse(res.failInfo)?.map((item: string) => {
                      return <div key={item}>{item}</div>
                    })
                    notification.open({
                      type: 'warning',
                      message: res.msg,
                      description: failInfo,
                    })
                  }
                }}
              >
                打印出库通知单
              </PermissionButton>
              {isRoot && menuItems.length > 0 && (
                <Dropdown
                  disabled={tableProps.loading}
                  placement="bottomLeft"
                  menu={{
                    items: menuItems,
                    onClick: handleClickMore,
                  }}
                >
                  <Button>
                    更多操作
                    <DownOutlined />
                  </Button>
                </Dropdown>
              )}
              <Checkbox
                disabled={tableProps.loading}
                onChange={(event: any) => {
                  setexpand(event.target.checked)
                }}
                style={{ marginTop: 18 }}
              >
                显示明细
              </Checkbox>
            </div>
            <div className="table_extra_flex">
              <PermissionButton
                permission="exportDeliver"
                onClick={async () => {
                  const paramsData: Record<string, any> = {}
                  if (selectedRowKeys.length > 0) {
                    paramsData.reserveInvoiceIds = selectedRowKeys
                  } else {
                    Object.assign(paramsData, params)
                  }
                  setexportLoading(true)
                  setspinning(true)
                  const res = await reserveInvoiceExport(paramsData)
                    .catch(() => setspinning(false))
                    .finally(() => {
                      setexportLoading(false)
                      setselectedRowKeys([])
                      setselectedRowInfos([])
                    })
                  if (res?.code === 200 && res?.data) {
                    await exportNotification(res?.data, navigate).finally(() => setspinning(false))
                  }
                }}
                icon={<UploadOutlined />}
                disabled={tableProps.loading || exportLoading}
              >
                导出
              </PermissionButton>
            </div>
          </div>
        }
      ></SearchForm>
      <CustomTable
        bordered
        isSelection
        selectRows={selectRows}
        selectedRowKeys={selectedRowKeys}
        columns={useIndexColumns({
          navigate,
          onView,
          onViewLogs,
          onConfirmDelivery,
          onSubmitPacking,
          onDel,
          onFix,
          isRoot,
        })}
        {...tableProps}
        expandable={{
          expandedRowKeys,
          expandedRowRender,
          onExpandedRowsChange: (keys: React.Key[]) => {
            setexpandedRowKeys(keys)
          },
        }}
        rowKey={(rows) => rows.reserveInvoiceId}
        tableRowGray={(record) =>
          record.reserveInvoiceStatus && record.reserveInvoiceStatus == 5 ? 'table-row-gray' : ''
        }
        isScrollY
      />
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
      <Drawer
        title="确认发货"
        maskClosable
        open={deliveryModalShow}
        onClose={onCancel}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={onCancel}>取消</Button>
              <Button type="primary" onClick={() => FormDelivery.validateFields().then((values) => onDelivery(values))}>
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical editConfig={useFormDelivery({ SupplierCYOption, getSupList })} form={FormDelivery} />
      </Drawer>
      <Drawer title="物流信息" maskClosable open={viewdeliveryModalShow} onClose={onCancel}>
        <EditFormVertical editConfig={useFormViewDelivery({ CurrentInfo })} form={FormViewDelivery} />
      </Drawer>
      <Modal title="预约发货" open={isModalShow} onCancel={onCancel} onOk={onSendOk}>
        <Form form={FormSend} layout="vertical">
          <Form.Item
            label="预约发货时间"
            name="scheduleDeliveryTime"
            style={{ marginBottom: 0 }}
            rules={[
              {
                required: true,
                message: '请选择预约发货时间',
              },
            ]}
          >
            <DatePicker showTime></DatePicker>
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="修正到货时间"
        open={FixModal.open}
        maskClosable
        onCancel={FixModal.closeModal}
        footer={
          <div className="flex_end">
            <Space>
              <Button onClick={FixModal.closeModal}>取消</Button>
              <Button
                type="primary"
                loading={FixModal.confirmLoading}
                onClick={() => {
                  FixModal.handleSubmit((vals) =>
                    fixArrivalTime({
                      ...vals,
                      reserveInvoiceId: FixModal.currentRecord?.reserveInvoiceId || null,
                      reserveInvoiceCode: FixModal.currentRecord?.reserveInvoiceCode || null,
                    }),
                  )
                }}
              >
                确定
              </Button>
            </Space>
          </div>
        }
      >
        <EditFormVertical
          editConfig={[
            {
              name: 'arrivalTime',
              label: '修正到货时间',
              type: 'FixedDatePicker',
              placeholder: '请选择修正到货时间',
              config: {
                customFormat: 'YYYY-MM-DD HH:mm:ss',
              },
              rules: [
                {
                  required: true,
                  message: '请选择修正到货时间',
                },
              ],
            },
            {
              name: 'updateArrivalTimeRemark',
              label: '修正备注',
              type: 'TextArea',
              placeholder: '请输入修正备注',
              config: {
                rows: 3,
              },
              rules: [
                {
                  required: true,
                  message: '请输入修正备注',
                },
              ],
            },
          ]}
          form={FixModal.form}
        />
      </Modal>
      <GenerateModal
        modalInstance={GenerateModalInstance}
        reqestFunction={createTransportationOrder}
        openModal={() => AddressModalInstance.openModal()}
        addressList={addressList}
      ></GenerateModal>
      <AddressModal
        modalInstance={AddressModalInstance}
        reqestFunction={addAddressReq}
        addressList={addressList}
        setaddressList={setaddressList}
        selectedRowInfos={selectedRowInfos}
        getAddressList={getAddressList}
      ></AddressModal>
      <Spin spinning={spinning} fullscreen />
    </PageContainer>
  )
}

export default Index
